<script setup>
import SendCaptcha from '@/components/user/SendCaptcha.vue'
import { ref, computed, inject } from 'vue'
import { ElMessage } from 'element-plus'
import userApi from '@/apis/user'

const emit = defineEmits(['success'])
const props = defineProps({
  type: String,
  account: String,
  unbind: Boolean,
})
const isSmallPage = inject('isSmallPage')
const dialogVisible = ref(false)

const captcha = ref('')
const newAccount = ref('')
const sendAccount = computed(() => (props.unbind ? props.account : newAccount.value))

const title = computed(() => (props.unbind ? '解绑' : '绑定'))
const typeTitle = computed(() => (props.type == 'email' ? '邮箱' : '手机号'))
const width = computed(() => (isSmallPage.value ? '95%' : '50%'))
const event = computed(() => (props.unbind ? 'unbind' : 'bind'))

const send = async () => {
  if (captcha.value.length < 4) {
    ElMessage.warning('请输入验证码')
    return
  }

  if (props.unbind) {
    await userApi.profile.unbind(props.type, props.account, captcha.value)
    ElMessage.success('解绑成功')
    emit('success', '')
  } else {
    await userApi.profile.bind(props.type, newAccount.value, captcha.value)
    ElMessage.success('绑定成功')
    emit('success', newAccount.value)
  }
  captcha.value = ''
  dialogVisible.value = false
}
</script>

<template>
  <el-button v-bind="$attrs" @click="dialogVisible = true">{{ title }}</el-button>
  <el-dialog v-model="dialogVisible" :title="title" :width="width" append-to-body>
    <el-form label-width="80px">
      <el-form-item :label="typeTitle">
        <el-input v-model="newAccount" placeholder="请输入新账号" v-if="!props.unbind" />
        <span v-else>{{ props.account }}</span>
      </el-form-item>
      <el-form-item label="验证码">
        <el-input v-model="captcha" placeholder="请输入验证码">
          <template #append>
            <SendCaptcha :type="props.type" :account="sendAccount" :event="event" />
          </template>
        </el-input>
      </el-form-item>
      <div class="mx-auto py-3 text-center">
        <el-button type="primary" @click="send">{{ title }}</el-button>
        <el-button @click="dialogVisible = false">取消</el-button>
      </div>
    </el-form>
  </el-dialog>
</template>
